import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Base64;

//TIP To <b>Run</b> code, press <shortcut actionId="Run"/> or
// click the <icon src="AllIcons.Actions.Execute"/> icon in the gutter.
public class Main {
    public static String imageToBase64(String imagePath) {
        File file = new File(imagePath);
        try (FileInputStream imageInFile = new FileInputStream(file)) {
            // 创建一个字节数组来存储图片数据
            byte[] imageData = new byte[(int) file.length()];
            // 读取图片数据到字节数组中
            imageInFile.read(imageData);

            // 对字节数组进行Base64编码并转换为字符串
            return Base64.getEncoder().encodeToString(imageData);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) {
        String imagePath = "C:\\Users\\njitzx\\Downloads\\数据库笔记.jpg"; // 替换为你的图片路径
        String base64String = imageToBase64(imagePath);
        if (base64String != null) {
            System.out.println("Base64编码结果：");
            System.out.println(base64String);
        } else {
            System.out.println("图片编码失败");
        }
    }
}
